package srv

import (
	"bytes"
	"io"
	"io/ioutil"

	"github.com/gin-gonic/gin"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/log"
)

// CopyBody 复制body数据到缓冲区
func CopyBody() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer c.Next()

		req := c.Request

		if req.Body == nil {
			return
		}
		log.Info("copy body 插件")
		safe := &io.LimitedReader{R: req.Body, N: 4096}
		requestbody, _ := ioutil.ReadAll(safe)
		req.Body.Close()
		bf := bytes.NewBuffer(requestbody)
		c.Request.Body = ioutil.NopCloser(bf)
		c.Set("Body", requestbody)
	}
}
